schedule = require "node-schedule"
db = require "./db"
utils = require "./utils"
_ = require "lodash"
dayjs = require "dayjs"
schedule.scheduleJob "* * * * *", ->
  console.log "batch send  " + dayjs().format "MM-DD HH:mm"
  day = new Date().getDay()
  date = new Date().getDate()
  query = mode: 2
  # query["weekdays." + day] = true
  sends = await db.SEND.find query
  for send in sends

    daytimes = send.daytime.split(' ')
    time1= dayjs().format("H:mm")
    time2= dayjs().format("HH:mm")

    if daytimes.includes(time1) or daytimes.includes(time2)
      try
        console.log "send task " + send.name
        if send?.month - 1 is 0
          if send.days.split(" ").includes date.toString()
            await utils.send.doSend send._id
        else
          if send.weekdays[day]
            await utils.send.doSend send._id
      catch e
        console.log e

schedule.scheduleJob "* * * * *", ->
  console.log "open draw" + dayjs().format "MM-DD HH:mm"

  draws =
    await db.POINT_DRAW.find
      status: 0
      opentime: $lte: new Date()

  for draw in draws
    rewards = _.sampleSize(draw.users, draw.stock) || []

    continue if rewards.length is 0
    console.log rewards
    await db.POINT_DRAW.findOneAndUpdate
      _id: draw._id
    ,
      $set:
        rewards: rewards
        status: 1

    client = await db.CLIENT.findOne draw.clientid
    rooms =
      await db.ROOM.find
        inviterid: client.contactid
        expires: $gt: new Date()

    rewardsname = rewards
      .map (a) -> a.nickname
      .join ","

    tips = draw.tips.replace("{{中奖者}}", rewardsname).replace "{{奖品名}}", draw.name

    sended = {}
    for room in rooms
      continue if sended[room.id]
      try
        sended[room.id] = true
        await bot.Room.load(room.id).say tips
      catch err
        console.log err
